import logging
import string
import traceback
import datetime
import logging
import logging.config
import os

from waitress import serve
from flask_cors import CORS
from flask import Blueprint, request, jsonify, Flask


app = Flask(__name__)


def create_app(config=None):
    from webapi import routes
    from webapi.routes.transform import transform_controller
    CORS(app)
    routes.init_app(app)

    # load default configuration
    # app.config.from_object('project.settings')
    # load environment configuration
    if 'FLASK_CONF' in os.environ:
        app.config.from_envvar('FLASK_CONF')
    # load app specified configuration
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)

    app.register_blueprint(transform_controller)

    print(app.url_map)

    return app


def create_logger():
    from logging.handlers import RotatingFileHandler

    logpath = os.path.normpath('logs/py_log.log')
    logdir = os.path.dirname(logpath)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    logging.basicConfig(
        handlers=[RotatingFileHandler(filename=os.path.normpath('logs/py_log.log'),
                                      mode='a', maxBytes=5000000, backupCount=10)],
        level=logging.DEBUG,
        format="[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s",
        datefmt='%Y-%m-%dT%H:%M:%S')

    logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
    rootLogger = logging.getLogger()

    consoleHandler = logging.StreamHandler()
    consoleHandler.setFormatter(logFormatter)
    rootLogger.addHandler(consoleHandler)


app = create_app()
create_logger()
# app = Flask(__name__)


@app.route('/')
def hello_world():
    return 'markdown-processing api is ON'


if __name__ == '__main__':
    logger = logging.getLogger("__main__")
    logger.info("program started ...")
    serve(app, host='0.0.0.0', port=18081)
    # app.run()
